package com.niji.littly_donkey_android.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.activity.GetPhoneCodeActivity;
import com.niji.littly_donkey_android.activity.IndexActivity;
import com.niji.littly_donkey_android.bean.Comment;
import com.niji.littly_donkey_android.bean.Photo;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.*;
import com.niji.littly_donkey_android.view.CircleImageView;
import com.niji.littly_donkey_android.view.StarRatingView;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IndexCommentAdapter extends ArrayAdapter<Comment> {


    private static final String TAG = "IndexCommentAdapter";

    private Context context;

    private Activity activity;

    private int flag = 0;

    public IndexCommentAdapter(Context context, ArrayList<Comment> members)
    {
        super(context,0, members);
        this.context = context;
        this.activity = (Activity) context;
    }
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Comment comment = getItem(position);

        if(convertView == null)
        {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_index_comment, parent, false);
        }

        CircleImageView roundedImageView = convertView.findViewById(R.id.index_comment_head);
        TextView commentTitle = convertView.findViewById(R.id.index_comment_nickname);
        TextView commentId = convertView.findViewById(R.id.index_comment_id);
        TextView commentMessage = convertView.findViewById(R.id.index_comment_content);
        TextView commentTime = convertView.findViewById(R.id.index_comment_time);
//        Button index_comment_send = convertView.findViewById(R.id.index_comment_send);
//        EditText index_comment_text = convertView.findViewById(R.id.index_comment_text);
        RelativeLayout show_child_comment = convertView.findViewById(R.id.show_child_comment);
        TextView show_child_comment_text = convertView.findViewById(R.id.show_child_comment_text);
        Button show_child_comment_btn = convertView.findViewById(R.id.show_child_comment_btn);
        Button not_show_child_comment_btn = convertView.findViewById(R.id.not_show_child_comment_btn);
        Button index_comment_likecount = convertView.findViewById(R.id.index_comment_likecount);
        ListView index_comment_child_comment = convertView.findViewById(R.id.index_comment_child_comment);
        //thumb.setImageBitmap(BitMap.getInstance().returnBitMap(u.getThumb()));
        if (comment.isLike()){
            Drawable drawable = convertView.getResources().getDrawable(R.mipmap.smallheart);
            drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
            index_comment_likecount.setCompoundDrawables(null,drawable,null,null);
        }else {
            Drawable drawable = convertView.getResources().getDrawable(R.mipmap.smallgreyheart);
            drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
            index_comment_likecount.setCompoundDrawables(null,drawable,null,null);
        }
        NetworkGlideImageLoader.getInstance().displayImage((Activity) context, comment.getHead(), roundedImageView,34,34);
        ArrayList<Comment> comments = (ArrayList<Comment>) comment.getComments();
        if(comments != null){
            index_comment_child_comment.setAdapter(new IndexChildCommentAdapter(context,comments));
        }
        if (comments == null) {
            show_child_comment.setVisibility(View.GONE);
            index_comment_child_comment.setVisibility(View.GONE);
        }else{
            if (comments.size() == 0){
                show_child_comment.setVisibility(View.GONE);
                index_comment_child_comment.setVisibility(View.GONE);
            }else {
                show_child_comment.setVisibility(View.VISIBLE);
                index_comment_child_comment.setVisibility(View.GONE);
                ViewGroup.LayoutParams layoutParams = index_comment_child_comment.getLayoutParams();
                ListAdapter listAdapter = index_comment_child_comment.getAdapter();
                View listItem = listAdapter.getView(0, null, index_comment_child_comment);
                listItem.measure(0, 0);
                int measuredHeight = listItem.getMeasuredHeight();
                layoutParams.height = comments.size() * measuredHeight;
                index_comment_child_comment.setLayoutParams(layoutParams);
                show_child_comment_text.setText("—— 展开" + comments.size() + "条回复");
                show_child_comment_btn.setVisibility(View.VISIBLE);
                not_show_child_comment_btn.setVisibility(View.GONE);
            }
        }
        show_child_comment_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index_comment_child_comment.setVisibility(View.VISIBLE);
                show_child_comment_text.setText("—— 收回" + comments.size() + "条回复");
                show_child_comment_btn.setVisibility(View.GONE);
                not_show_child_comment_btn.setVisibility(View.VISIBLE);
            }
        });
        not_show_child_comment_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index_comment_child_comment.setVisibility(View.GONE);
                show_child_comment_text.setText("—— 展开" + comments.size() + "条回复");
                show_child_comment_btn.setVisibility(View.VISIBLE);
                not_show_child_comment_btn.setVisibility(View.GONE);
            }
        });
        View finalConvertView = convertView;
        index_comment_likecount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(comment.isLike());
                if(!comment.isLike()){
                    String url = UrlUtil.URL + "/user/comments/log/likes";
                    RequestQueue requestQueue= Volley.newRequestQueue(context);
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            try {
                                Map<String, Object> map = JsonUtil.jsonToMap(s);
                                Integer code = (Integer) map.get("code");
                                if (code == 0) {
                                    Drawable drawable = finalConvertView.getResources().getDrawable(R.mipmap.smallheart);
                                    drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                                    index_comment_likecount.setCompoundDrawables(null,drawable,null,null);
                                    Toast.makeText(context, "点赞成功", Toast.LENGTH_LONG).show();
                                    String num = index_comment_likecount.getText().toString().trim();
                                    index_comment_likecount.setText("" + (Integer.parseInt(num) + 1 ));
                                    flag = 1;
                                    comment.setLike(true);
                                } else if(code == -1){
                                    Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                                    intent.putExtra("loginCode","-1");
                                    activity.startActivity(intent);
                                    activity.finish();
                                }else {
                                    Object message = map.get("message");
                                    Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                                    activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                    activity.finish();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e(TAG, volleyError.getMessage(), volleyError);
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("comments_id",String.valueOf(comment.getId()));
                            return map;
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            String sesseionid = new ConnectViaSession(context).GetSession();
                            if (!sesseionid.equals("")) {
                                HashMap<String, String> headers = new HashMap<String, String>();
                                headers.put("cookie", sesseionid);
                                return headers;
                            } else {
                                return super.getHeaders();
                            }
                        }
                    };

                    requestQueue.add(stringRequest);
                }else{
                    String url = UrlUtil.URL + "/user/comments/cancel/likes?comments_id=" + comment.getId();
                    RequestQueue requestQueue= Volley.newRequestQueue(context);
                    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            try {
                                Map<String, Object> map = JsonUtil.jsonToMap(s);
                                Integer code = (Integer) map.get("code");
                                if (code == 0) {
                                    Drawable drawable = finalConvertView.getResources().getDrawable(R.mipmap.smallgreyheart);
                                    drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                                    index_comment_likecount.setCompoundDrawables(null,drawable,null,null);
                                    Toast.makeText(context, "取消点赞成功", Toast.LENGTH_LONG).show();
                                    String num = index_comment_likecount.getText().toString().trim();
                                    index_comment_likecount.setText("" + (Integer.parseInt(num) - 1 ));
                                    flag = 0;
                                    comment.setLike(false);
                                } else if(code == -1){
                                    Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                                    intent.putExtra("loginCode","-1");
                                    activity.startActivity(intent);
                                    activity.finish();
                                }else {
                                    Object message = map.get("message");
                                    Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                                    activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                    activity.finish();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e(TAG, volleyError.getMessage(), volleyError);
                        }
                    }) {

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            String sesseionid = new ConnectViaSession(context).GetSession();
                            if (!sesseionid.equals("")) {
                                HashMap<String, String> headers = new HashMap<String, String>();
                                headers.put("cookie", sesseionid);
                                return headers;
                            } else {
                                return super.getHeaders();
                            }
                        }
                    };

                    requestQueue.add(stringRequest);
                }

            }
        });
        commentTime.setText(comment.getTime());
        index_comment_likecount.setText("" + comment.getLikes());
        commentId.setText("" + comment.getId());
        commentMessage.setText(comment.getMessage());
        commentTitle.setText(comment.getTitle());
        return convertView;
    }




}



